
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package be.ac.ua.pats.thesisrobotica.robot.communication;

//~--- non-JDK imports --------------------------------------------------------

import lejos.nxt.comm.*;

//~--- JDK imports ------------------------------------------------------------

import java.io.*;

/**
 *
 * @author Admin
 */
public class USBConnection implements Connection {
    boolean                      connected = false;
    lejos.nxt.comm.USBConnection connection;
    DataInputStream              iStream;
    DataOutputStream             oStream;

    public USBConnection() {
        connection = USB.waitForConnection();
        connected  = true;

        OutputStream os = connection.openOutputStream();
        InputStream  is = connection.openInputStream();

        oStream = new DataOutputStream(os);
        iStream = new DataInputStream(is);
    }

    public boolean isConnected() {
        return connected;
    }

    public void send(String s) {
        try {
            oStream.writeUTF(s);
            oStream.flush();
        } catch (IOException ex) {}
    }

    public void disconnect() {
        try {
            connected = false;

            iStream.close();
            oStream.close();
            connection.close();
        } catch (IOException ex) {}
    }

    public void run() {
        try {
            StringBuilder resString = new StringBuilder();

            while (connected) {
                int  stringLength = iStream.readInt();
                char n;

                for (int i = 0; i < stringLength; i++) {
                    n = iStream.readChar();

                    resString.append(n);
                }

                resString = new StringBuilder();
            }
        } catch (IOException ex) {}
    }
}
